// myMixins.js
import * as echarts from 'echarts'
import {adata} from '@/views/customer/health/mixin/adata'

export const detailMixins = {
  components: {},
  data() {
    return {
      param: {
        mb_h: [],
        mb_l: [],
        jy_h: [],
        jy_l: [],
        xData: new Array(1201).fill(''),
        mb: new Array(1201).fill(null),
        _mb: new Array(1201).fill(null),
        jy: new Array(1201).fill(null),
        currentIndex: 1,
        size: 0,
        intervalFlag: false,
        speed: 10,
        peaks: [],
        _peaks: [],
        max: 2933.8,
        initTitle: '脉率：   ，波长：  ms， 波幅：',
        interval: null,
        myChart: null
      },

    }
  },
  created() {
    this.getData()
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    getData() {
      adata[1].forEach(([first, second, third, fourth]) => {
        this.param.jy_l.push(first)
        this.param.jy_h.push(second)
        this.param.mb_l.push(third)
        this.param.mb_h.push(fourth)
      })
    },
    init() {
      this.myChart = echarts.init(this.$refs.chart)
      this.myChart.getZr().on('dblclick', params => {
        // console.log('双击事件触发')
        if (this.param.intervalFlag) {
          this.stopInterval()
        } else {
          this.startInterval()
        }
      })
      // 使用刚指定的配置项和数据显示图表。
      this.myChart.setOption(this.getOptions())

      this.startInterval()
    },
    getOptions() {

      return {
        color: ['#428DF9', '#95CEF3'],
        title:{
          textStyle: {
            color: '#FFFFFF'
          },
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (t) {
            if (t) {
              let e = ''
              e += t[0].name.replace(/\-/g, '/') + '<br/>'
              for (let n = 0; n < t.length; n++) {
                const o = t[n]
                e += '<div>',
                  e += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + o.color + ';"></span>',
                  e += o.seriesName + '\uff1a' + o.value,
                  e += '</div>'
              }
              return e
            }
          },
          backgroundColor: '#ccc',
          borderWidth: 1,
          borderColor: '#ccc',
          padding: 10,
          textStyle: {
            color: '#000',
            fontSize: 12,
            align: 'left'
          }
        },
        legend: {
          show: !0,
          x: 'center',
          y: '10px',
          data: [{
            name: '脉搏/强度&脉率',
            textStyle: {
              color: '#428DF9'
            }
          }, {
            name: '静压/深度',
            textStyle: {
              color: '#95CEF3'
            }
          }]
        },
        xAxis: {
          type: 'category',
          scale: !0,
          data: this.param.xData,
          axisTick: {
            alignWithLabel: !0
          },
          axisLine: {
            onZero: !1,
            lineStyle: {
              color: '#01efef'
            }
          },
          axisLabel: {
            textStyle: {
              color: '#01efef'
            },
            // 添加间隔设置，避免标签过于密集
            interval: (index, value) => {
              // 每隔一定数量的点显示一个标签，可以根据需要调整
              return index % 100 === 0;
            }
          }
        },
        yAxis: [{
          type: 'value',
          name: '脉搏/强度&脉率',
          nameLocation: 'center',
          nameGap: 50,
          nameTextStyle: {
            color: '#428DF9'
          },
          axisLabel: {
            color: '#428DF9'
          },
          axisLine: {
            lineStyle: {
              show: true,
              color: '#ff0000' // 设置y轴颜色为红色
            }
          },
          calculateMinMax: true,
          inverse: false, // 确保刻度顺序正确
          /* min: function(t) {
            if(t){
              return 1e3 * (Math.floor(t.min / 1e3) - 1)
            }
            return -2000   //-600
          },
          max: function(t) {
            if(t){

              return 1e3 * (Math.floor(t.max / 1e3) + 1)
            }
            return 3000     //600
          }, */
          splitLine: {
            show: !1
          }
        }, {
          type: 'value',
          name: '静压/深度',
          nameLocation: 'center',
          nameGap: 50,
          nameTextStyle: {
            color: '#95CEF3'
          },
          axisLabel: {
            color: '#95CEF3'
          },
          axisLine: {
            lineStyle: {
              color: '#ff0000' // 设置y轴颜色为红色
            }
          },
          calculateMinMax: true,
          inverse: false, // 确保刻度顺序正确
          /* min: function(t) {
            if(t){
              return 1e3 * (Math.floor(t.min / 1e3) - 1)
            }
            //return 10000
          },
          max: function(t) {
            if(t){

              return 1e3 * (Math.floor(t.max / 1e3) + 1)
            }
            return 14000
          }, */
          splitLine: {
            show: !1
          }
        }],
        series: [this.param.mb, this.param.jy].map((e, n) => ({
          name: n === 0 ? '脉搏/强度&脉率' : '静压/深度',
          data: e,
          type: 'line',
          symbol: 'none',
          smooth: !0,
          yAxisIndex: n
        }))
      }
    },

    getAndRemoveLeftNElements(arr, n) {
      if (!arr || arr.length === 0) return []

      // 限制 n 的范围，防止超出数组长度
      n = Math.min(n, arr.length)

      // 使用 splice 方法删除并返回前 n 个元素
      return arr.splice(0, n)
    },
    stopInterval() {
      clearInterval(this.param.interval)
      this.param.intervalFlag = false
    },
    startInterval() {
      this.param.interval = setInterval(() => {
        this.handleChart()
      }, 500)
    },
    handleChart(){
      this.param.mb.splice(0, this.param.speed)
      this.param._mb.splice(0, this.param.speed)
      this.param.jy.splice(0, this.param.speed)
      this.param.xData.splice(0, this.param.speed)
      if (this.param.mb_l.length > 0) {
        let c_mb_l = this.getAndRemoveLeftNElements(this.param.mb_l, this.param.speed)
        let c_mb_h = this.getAndRemoveLeftNElements(this.param.mb_h, this.param.speed)
        let c_jy_l = this.getAndRemoveLeftNElements(this.param.jy_l, this.param.speed)
        let c_jy_h = this.getAndRemoveLeftNElements(this.param.jy_h, this.param.speed)

        c_mb_l.forEach((value, index) => {
          this.param.mb.push(this.int16Overflow(value + 256 * c_mb_h[index]) / 10)
          this.param._mb.push(-(this.int16Overflow(value + 256 * c_mb_h[index]) / 10))
          this.param.jy.push(this.int16Overflow(c_jy_l[index] + 256 * c_jy_h[index]) * 10)

        })
        this.param.peak = this.findPeaks(this.param.mb, 100, 200, this.param.max)
        this.param._peak = this.findPeaks(this.param._mb, 100, 200, this.param.max)
        // this.param.title = String.format("mailv "+ Math.round(60 * 1000.0 / (peak.get(1) - peak.get(0)) / 5)+" bochang: "+(peak.get(1) - peak.get(0)) * 5+" ms bofu "+  Math.floor(mb.get(peak.get(0)) - mb.get(_peak.get(0))));
        if (this.param.peak.length >= 2) {
          this.param.title = '脉率: ' + Math.round(60 * 1000.0 / (this.param.peak[1] - this.param.peak[0]) / 5) + ', 波长: ' + (this.param.peak[1] - this.param.peak[0]) * 5 + ' ms , 波幅： ' + Math.floor(this.param.mb[this.param.peak[0]] - this.param.mb[this.param._peak[0]])
        } else {
          this.param.title = this.param.initTitle
        }

      } else {
        /*this.param.title = this.param.initTitle
        this.stopInterval()*/
        this.getData()
        this.handleChart()
        return
      }
      Array.from({length: this.param.speed}, (_, i) => {
        // 在此处处理每一个值 i
        // console.log(i) // 例如，打印每个值
        this.param.xData.push((0.005 * this.param.currentIndex).toFixed(3) + 's')
        this.param.currentIndex++
      })
      this.myChart.setOption({
        series: [this.param.mb, this.param.jy].map((e, n) => ({
          data: e
        })),
        xAxis: {
          data: this.param.xData
        },
        title: {
          text: this.param.title,
          left: '300', // 将标题水平居中
          top: 'top', // 将标题垂直顶部对齐
          textStyle: {
            color: '#FFFFFF'
          },
        }
      })
      this.param.intervalFlag = true
    },
    findPeaks(data, minDistance, minHeight, maxHeight) {
      const peaks = []

      // 检查输入的有效性
      if (!Array.isArray(data) || data.length < 2 * minDistance + 1) {
        throw new Error('Data array is too short or not an array.')
      }

      // 初始化前一个最大值
      let prevValue = data[0]
      let prevIndex = 0

      for (let i = 1; i < data.length; i++) {
        if (data[i] === null || data[i] === undefined) continue
        if (data[i] > prevValue) {
          // 如果当前值大于前一个值，则可能是一个上升趋势
          prevValue = data[i]
          prevIndex = i
        } else if (data[i] < prevValue) {
          // 如果当前值小于前一个值，检查前一个值是否为局部最大值
          if (i - prevIndex >= minDistance && prevValue >= minHeight && prevValue <= maxHeight) {
            peaks.push(prevIndex)
            prevValue = data[i]
            prevIndex = i
          }
        }
        // 注意：原Java代码中有注释掉的部分处理连续相同值的情况，这里我们省略了这个部分，
        // 因为它被注释掉了，并且在大多数情况下不需要处理连续相同的值。
      }

      // 检查最后一个可能的峰值
      if (prevValue >= minHeight && prevValue <= maxHeight && data.length - 1 - prevIndex >= minDistance) {
        peaks.push(prevIndex)
      }

      return peaks
    },
    int16Overflow(num) {
      let result = num & 0xFFFF // 使用按位与运算符将数字限制在16位范围内
      if (result > 32767) { // 如果结果大于32767（int16的最大值）
        result -= 65536 // 减去65536以实现溢出
      } else if (result < -32768) { // 如果结果小于-32768（int16的最小值）
        result += 65536 // 加上65536以实现溢出
      }
      return result
    }
  }
}
